package com.sunlands.deskmate.channel;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * @author lishuai
 *
 */
@Component
public class NettyWebSocketServer implements CommandLineRunner {

    @Value("${netty.server.port}")
    private int port;

    @Value("${netty.server.backlog}")
    private int backlog;

    @Value("${netty.server.parentgroup.size}")
    private int parentGroupSize;

    @Value("${netty.server.childgroup.size}")
    private int childGroupSize;

    @Resource
    private ChildChannelHandler childChannelHandler;

    @Override
    public void run(String... strings) throws Exception {
        start(port);
    }


    public void start(int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(parentGroupSize);
        EventLoopGroup workerGroup = new NioEventLoopGroup(childGroupSize);
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(childChannelHandler);
        try {
            bootstrap.bind(port).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
